package org.zhaozhen.basic.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zhaozhen.basic.util.AjaxResult;
import org.zhaozhen.basic.util.FastDfsUtil;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    @PostMapping("/upload")//当接受的参数为文件时，使用@RequestPart注解
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){

        try {
            //获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg
            //获取文件名后缀
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            System.out.println(extName);
            //调用工具类方法，将文件转为bytes格式，和文件后缀传过去
            String result =  FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(result); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败!"+e.getMessage());
        }
    }
    /**
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     *
     */
    @DeleteMapping
    public AjaxResult remove(@RequestParam(required = true, value = "path") String path) {
        try {
            String pathTmp = path.substring(1); // group1/M00/01/A6/rBE3kWGYoBKARKHCAAFeHybleuQ941.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);//   M00/01/A6/rBE3kWGYoBKARKHCAAFeHybleuQ941.jpg
            FastDfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,稍后重试!!!!");
        }

    }

}
